package org.budo.wxpay.api;

import java.io.InputStream;

import org.budo.support.lang.util.StringUtil;
import org.budo.wxpay.util.WxpayUtil_0;

import com.github.wxpay.sdk.WXPay;
import com.github.wxpay.sdk.budo.BudoWXPayConfig;

import lombok.Getter;
import lombok.Setter;
import lombok.experimental.Accessors;

/**
 * @author lmw
 */
@Getter
@Setter
@Accessors(chain = true)
public abstract class AbstractWxPayApi implements WxPayApi {
    private String appId;

    private String mchId;

    private String notifyUrl;

    private String apiKey;

    private InputStream certStream;

    protected WXPay wxpay(AbstractWxPayRequest request) {
        String appId = request.getAppId();
        if (StringUtil.isNullOrEmpty(appId)) {
            appId = this.getAppId();
        }

        if (StringUtil.isNullOrEmpty(appId)) {
            throw new IllegalArgumentException("#236 appId is null");
        }

        String mchId = request.getMchId();
        if (StringUtil.isNullOrEmpty(mchId)) {
            mchId = this.getMchId();
        }

        if (StringUtil.isNullOrEmpty(mchId)) {
            throw new IllegalArgumentException("#245 mchId is null");
        }

        String apiKey = request.getApiKey();
        if (StringUtil.isNullOrEmpty(apiKey)) {
            apiKey = this.getApiKey();
        }

        if (StringUtil.isNullOrEmpty(apiKey)) {
            throw new IllegalArgumentException("#254 apiKey is null");
        }

        BudoWXPayConfig config = new BudoWXPayConfig(appId, mchId, apiKey);
        InputStream certStream = request.getCertStream();
        if (null == certStream) {
            certStream = this.getCertStream();
        }

        if (null != certStream) {
            config.setCertStream(certStream);
        }

        return WxpayUtil_0.newWXPay(config);
    }

    protected String notifyUrl(UnifiedOrderRequest request) {
        String notifyUrl = request.getNotifyUrl();
        if (StringUtil.isNullOrEmpty(notifyUrl)) {
            notifyUrl = this.getNotifyUrl();
        }

        if (StringUtil.isNullOrEmpty(notifyUrl)) {
            throw new IllegalArgumentException("#263 notifyUrl can not be null, notifyUrl=" + notifyUrl);
        }

        return notifyUrl;
    }
}